package org.datastealer.config;


import org.apache.catalina.connector.Connector;
import org.datastealer.properties.DataStealerProperties;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Note：
 *
 * @author ：mengjw
 * @description：Tomcat配置类
 * @date ：Created in 2020/8/22
 */
@ConditionalOnClass(EmbeddedServletContainerCustomizer.class)
public class DataStealerTomcatConfiguration implements ApplicationContextAware, EmbeddedServletContainerCustomizer {

    protected static ApplicationContext CONTEXT;

    /**
     * 获取上下文
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    /**
     * 根据配置增加端口的监听
     *
     * @param container
     */
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        DataStealerProperties dataStealerProperties = CONTEXT.getBean(DataStealerProperties.class);
        if (dataStealerProperties.newTomcatPortEnable && container instanceof TomcatEmbeddedServletContainerFactory) {
            // 转换类型为TomcatEmbeddedServletContainerFactory
            TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
            // Tomcat中，一个Container监听一个端口
            // 指定协议为HTTP/1.1
            Connector httpConnector = new Connector("HTTP/1.1");
            httpConnector.setPort(dataStealerProperties.newTomcatPort);
            tomcat.addAdditionalTomcatConnectors(httpConnector);
        }
    }

}